package com.sxhalo.fsms.quartz;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.websocket.Session;

import com.alibaba.fastjson.JSON;
import com.sxhalo.fsms.domain.RedisData;
import com.sxhalo.fsms.util.CacheUtil;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sxhalo.fsms.domain.MotorReliabilityData;
import com.sxhalo.fsms.domain.MotorRunningData;
import com.sxhalo.fsms.service.IMotorReliabilityDataService;
import com.sxhalo.fsms.service.IMotorRunningDataService;
import com.sxhalo.fsms.socket.WebSocketServer;
import com.sxhalo.fsms.util.DateUtil;

@DisallowConcurrentExecution // 作业不并发
@Component
public class ScheduledRunningTask implements Job {

	@Autowired
	private RedisTemplate<String, ?> redisTemplate;

	ObjectMapper objectMapper = new ObjectMapper();
	
	@Autowired
	private IMotorRunningDataService runService;
	
	@Autowired
	private IMotorReliabilityDataService relService;



	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		// NULL不参与序列化
		objectMapper.setSerializationInclusion(Include.NON_NULL);

		System.out.println("ScheduledRunningTask定时任务" + DateUtil.FormatTime(new Date()));

		HashOperations<String, Object, Object> redis = redisTemplate.opsForHash();
		// 所有的Socket连接
		Set<Session> map = WebSocketServer.getSessionSet();

		System.out.println(" - [SessionCount, " + map.size() + "] - ");

		for (Session session : map) {
			Map<String, Object> user = session.getUserProperties();
			if (user.get("deviceId") == null)
				continue;

			MotorRunningData runData = null;
			MotorReliabilityData relData = null;
			RedisData data=null;
			String deviceId = user.get("deviceId").toString();
			Map<String, Object> msgData = new HashMap<String, Object>();
			// redis 连接失败 如何处理
			try {
					data=CacheUtil.getredismap(deviceId);
					if(data==null){
						Map<Object, Object> rowData=redis.entries(deviceId);
						data= JSON.parseObject(JSON.toJSONString(rowData),RedisData.class);
					}
//					redis.entries(deviceId);
					//实时数据
					 data.setDeviceId(Integer.parseInt(deviceId));
				 	msgData.put("RunningData", data);

//				runData = getRunningData(deviceId, rowData);
//				relData = getReliabilityData(deviceId, rowData);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(" ---- [redis没连上] ----");
//				runData = runService.findLastData(deviceId);
//				relData = relService.selectByPrimaryKey(deviceId);
	//			runData.setOnline(0);//掉线
				data=new RedisData();
                data.setOnline(0);
				msgData.put("RunningData",data);
			}
			//消息发送
//			Map<String, Object> msgData = new HashMap<String, Object>();
//			msgData.put("ReliabilityData", relData);
//			msgData.put("RunningData", runData);
	//		msgData.put("RunningData", data);
			String json = null;
			try {
				json = objectMapper.writeValueAsString(msgData);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			if (json != null && session.isOpen()) {
				WebSocketServer.sendMessage(json, session);
			}
		}

		RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());

	}

	private MotorReliabilityData getReliabilityData(String deviceId, Map<Object, Object> rowData) {
		MotorReliabilityData relData = new MotorReliabilityData();
		relData.setAcquisitionTime(new Date());
		relData.setDeviceId(Integer.parseInt(deviceId));
		relData.setCurrentRuningHour(rowData.get("CurrentRuningHour")==null?null:Integer.parseInt(rowData.get("CurrentRuningHour").toString()));
		relData.setTotalRuningHour(rowData.get("TotalRuningHour")==null?null:Integer.parseInt(rowData.get("TotalRuningHour").toString()));
		relData.setTotalStart(rowData.get("TotalStart")==null?null:Integer.parseInt(rowData.get("TotalStart").toString()));
		relData.setTotalTrip(rowData.get("TotalTrip")==null?null:Integer.parseInt(rowData.get("TotalTrip").toString()));
		return relData;
	}
	
	private MotorRunningData getRunningData(String deviceId, Map<Object, Object> rowData) {
		MotorRunningData runData = new MotorRunningData();
		runData.setAcquisitionTime(new Date());
		runData.setDeviceId(Integer.parseInt(deviceId));
		runData.setReady(rowData.get("Ready")==null?null:Integer.parseInt(rowData.get("Ready").toString()));
		runData.setOnline(rowData.get("Online")==null?null:Integer.parseInt(rowData.get("Online").toString()));
		runData.setRunning(rowData.get("Running")==null?null:Integer.parseInt(rowData.get("Running").toString()));
		runData.setStart(rowData.get("Start")==null?null:Integer.parseInt(rowData.get("Start").toString()));
		runData.setAlarm(rowData.get("Alarm")==null?null:Integer.parseInt(rowData.get("Alarm").toString()));
		runData.setAlarmCode(rowData.get("AlarmCode")==null?null:rowData.get("AlarmCode").toString());
		runData.setTrip(rowData.get("Trip")==null?null:Integer.parseInt(rowData.get("Trip").toString()));
		runData.setTripCode(rowData.get("TripCode")==null?null:rowData.get("TripCode").toString());
		runData.setStartaRunningFlag(rowData.get("StartARunning")==null?null:Integer.parseInt(rowData.get("StartARunning").toString()));
		runData.setStartbRunningFlag(rowData.get("StartBRunning")==null?null:Integer.parseInt(rowData.get("StartBRunning").toString()));
		runData.setPhaseaCurrent(rowData.get("PhaseACurrent")==null?null:new BigDecimal(rowData.get("PhaseACurrent").toString()));
		runData.setPhasebCurrent(rowData.get("PhaseBCurrent")==null?null:new BigDecimal(rowData.get("PhaseBCurrent").toString()));
		runData.setPhasecCurrent(rowData.get("PhaseCCurrent")==null?null:new BigDecimal(rowData.get("PhaseCCurrent").toString()));
		runData.setUabLineVoltage(rowData.get("UabLineVoltage")==null?null:new BigDecimal(rowData.get("UabLineVoltage").toString()));
		runData.setUbcLineVoltage(rowData.get("UbcLineVoltage")==null?null:new BigDecimal(rowData.get("UbcLineVoltage").toString()));
		runData.setUcaLineVoltage(rowData.get("UcaLineVoltage")==null?null:new BigDecimal(rowData.get("UcaLineVoltage").toString()));
		runData.setActivePower(rowData.get("ActivePower")==null?null:new BigDecimal(rowData.get("ActivePower").toString()));
		runData.setReactivePower(rowData.get("ReactivePower")==null?null:new BigDecimal(rowData.get("ReactivePower").toString()));
		runData.setApparentPower(rowData.get("ApparentPower")==null?null:new BigDecimal(rowData.get("ApparentPower").toString()));
		runData.setPowerFactor(rowData.get("PowerFactor")==null?null:new BigDecimal(rowData.get("PowerFactor").toString()));
		runData.setCurrentUnbalance(rowData.get("CurrentUnbalance")==null?null:new BigDecimal(rowData.get("CurrentUnbalance").toString()));
		runData.setHeatCapacityPercentage(rowData.get("HeatCapacityPercentage")==null?null: new BigDecimal(rowData.get("HeatCapacityPercentage").toString()));
		return runData;
	}
}
